package util

import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"github.com/pkg/errors"
	"golang.org/x/crypto/pbkdf2"
)

// EncryptPassword 对用户输入的原始密码进行加密，使用pbkdf2算法加密，iter是加密迭代次数，keylen是生成salt的长度
func EncryptPassword(origin string, iter, keylen int) (salt, encryptedPassword string, err error) {
	saltByte := make([]byte, keylen)
	_, err = rand.Read(saltByte)
	if err != nil {
		return "", "", errors.New("Encrypt error " + err.Error())
	}
	dk := pbkdf2.Key([]byte(origin), saltByte, iter, keylen, sha256.New)
	encryptedPassword = hex.EncodeToString(dk)
	return hex.EncodeToString(saltByte), encryptedPassword, nil
}

// EncryptWithSalt  根据原始密码和salt来生成加密后的密码
func EncryptWithSalt(origin, salt string, iter, keylen int) (encryptedPassword string, err error) {
	saltByte, err := hex.DecodeString(salt)
	if err != nil {
		return "", errors.New("EncryptWithSalt error " + err.Error())
	}
	dk := pbkdf2.Key([]byte(origin), saltByte, iter, keylen, sha256.New)
	encryptedPassword = hex.EncodeToString(dk)
	return encryptedPassword, nil
}
